const Core = require('@alicloud/pop-core');
var db = require('../util/db')
const aliyConfig = require('../util/aliyConfig')
const fs = require('fs')
function rand(min, max) {
    return Math.floor(Math.random() * (max - min)) + min
}

var validatePhoneCode = []
//验证码1分钟后将删除
function Calculator(phone) {
    let timer = setTimeout(() => {
        console.log(phone + ':' + '验证码已删除')
        validatePhoneCode = validatePhoneCode.filter(item => item.phone != phone)
        clearTimeout(timer)
    }, 600000)

}
//检验手机号是否有验证码
function userPhoneHasCode(phone) {
    for (let v of validatePhoneCode) {
        if (v.phone === phone) {
            return true
        }
    }
    return false
}

//判断是否登陆成功
function loginPhoneAndCode(phone, code) {
    console.log(phone, code)
    for (let v of validatePhoneCode) {
        if (v.phone == phone && v.code == code) {
            return true
        }
    }
    return false
}

//判断是否是第一次登陆并注册
async function phoneAndCodeIsReg(phone) {
    let result = await db.sqlConnectSync('select * from user where phone = ?', [phone])
    if (result != 0) {
        return false
    }
    phoneReg(phone)
    return true
}

//第一次登陆并注册
async function phoneReg(phone) {
    let result = await db.sqlConnectSync('insert into user set ?', { phone })
    if (result.affectedRows != 0) {
        return false
    }
    return true
}

//注册用户基本信息和用户登陆信息
async function userInfoReg(user) {
    let { username, password, user_id, name, age, sex, job, email, phone, create_time } = user
    //是否已用手机注册
    if (phoneAndCodeIsReg(phone)) {
        let result = await db.sqlConnectSync('update user set username = ?,password = ?,phone = ?,email = ?,create_time = ? where phone = ?', [username, password, phone, email, create_time, phone])
        if (result.affectedRows != 0) {
            console.log(username + ':已填写信息')
        }
        if (result instanceof Error) {
            console.log(username + ':填写信息失败')
            return false
        }

    }
    result = await db.sqlConnectSync('insert into user_info set ?', { user_id, name, age, sex, job })
    if (result.affectedRows != 0) {
        console.log(username + ':用户基本信息注册成功')
        return true
    }
    return false
}

//获取用户基本信息
async function getUserInfo(user_id) {
    let result = await db.sqlConnectSync('select * from user_info where user_id = ?', [user_id])
    if (result?.length != 0) {
        return result
    } else {
        return res.send({
            err: '403',
            msg: '查询失败'
        })
    }
}

//修改用户基本信息
async function updateUserInfo(user) {
    let { user_id, name, age, sex, job } = user
    let result = await db.sqlConnectSync('update user_info set name = ?,age = ?,sex = ?,job = ? where user_id = ?', [name, age, sex, job, user_id])
    if (result?.affectedRows != 0) {
        return true
    } else {
        return false
    }
}


//发送验证码接口
exports.sendRand = (req, res) => {
    let { phone } = req.body
    let random = rand(1000, 9999)
    let client = new Core(aliyConfig)
    let params = {
        "SignName": "阿里云短信测试",
        "TemplateCode": "SMS_154950909",
        "PhoneNumbers": phone,
        "TemplateParam": JSON.stringify({ 'code': random })
    }
    let requestOption = {
        method: 'POST',
        formatParams: false,
    };
    if (!userPhoneHasCode(phone)) {
        validatePhoneCode.push({ phone, code: random })
        // client.request('SendSms', params, requestOption).then((result) => {
        // }, (ex) => {
        //     console.log(ex);
        // })
        Calculator(phone)
        return res.send({
            code: random,
            msg: '验证码发送成功'
        })
    } else {
        return res.send({
            err: '403',
            msg: '验证码发送失败'
        })
    }

}



//登陆接口
exports.login = (req, res) => {
    let { phone, code } = req.body
    console.log(phone, code)
    if (userPhoneHasCode(phone)) {
        if (loginPhoneAndCode(phone, code)) {
            phoneAndCodeIsReg(phone)
            return res.send({
                code: '200',
                msg: '登陆成功'
            })
        } else {
            return res.send({
                code: '200',
                msg: '登陆失败'
            })
        }
    }
    res.send({
        code: '200',
        msg: '未获取验证码,无法登陆'
    })
}

//注册用户信息接口
exports.userInfosReg = (req, res) => {
    let user_info = req.body
    console.log(user_info)
    if (userInfoReg(user_info)) {
        return res.send({
            code: '200',
            msg: '信息注册成功'
        })
    }
    return res.send({
        code: '200',
        msg: '信息注册失败'
    })
}

// 通过手机号/用户名和密码登陆
exports.loginPhoneorUnameAndPwd = async (req, res) => {
    let { username, password } = req.body
    if (!username && password) {
        return res.send({
            code: '200',
            msg: '用户名和密码不能为空'
        })
    }
    let result = await db.sqlConnectSync('select * from user where username = ? and password = ? or phone = ? and password = ?', [username, password, username, password])
    if (result.length == 0) {
        return res.send({
            code: '200',
            msg: '登陆失败,用户名或密码错误'
        })
    }
    return res.send({
        code: '200',
        msg: '登陆成功'
    })
}

//用户文件上传
exports.userImgUpload = async (req, res) => {
    res.set({
        'content-type': 'application/json; charset=utf-8'
    })
    //判断文件是否为空
    if (req.file.length === 0) {
        res.render("error", { message: "上传文件不能为空！" });
        return
    } else {
        let file = req.file
        //修改名字，第一个参数为旧路径，第二个参数为新路径（注意：旧路径要和上面的dest保持一致）
        fs.renameSync('./public/uploads/' + file.filename, './public/uploads/' + file.originalname)
        if (file) {
            let { user_id } = req.query
            let img_url = 'http://localhost/uploads/' + file.originalname
            let result = await db.sqlConnectSync('update user set userpic = ? where id = ?', [img_url, user_id])
            if (result?.affectedRows != 0) {
                return res.send({
                    code: '200',
                    msg: '上传成功'
                })
            } else {
                return res.send({
                    code: '500',
                    msg: result
                })
            }
        }
    }
}

//用户多文件上传
exports.userImgsUpload = async (req, res) => {
    res.set({
        'content-type': 'application/json; charset=utf-8'
    })
    let files = req.files
    //判断文件是否为空
    if (files.length === 0) {
        res.render("error", { message: "上传文件不能为空！" });
        return
    } else {
        let { user_id } = req.query
        let arr = []
        if (files) {
            let sql = `insert into user_pic(user_id,user_pic,create_time) values`
            for (let f of files) {
                //修改名字，第一个参数为旧路径，第二个参数为新路径（注意：旧路径要和上面的dest保持一致）
                fs.renameSync('./public/moreUploads/' + f.filename, './public/moreUploads/' + f.originalname)
                let img_url = 'http://localhost/moreUploads/' + f.originalname
                let newTime = new Date()
                arr.push([user_id, img_url, newTime.toLocaleString()])
                sql += '(?),'
            }
            let result = await db.sqlConnectSync(sql.slice(0, sql.length - 1), arr)
            if (result?.affectedRows != 0) {
                return res.send({
                    code: '200',
                    msg: '上传成功'
                })
            } else {
                return res.send({
                    code: '500',
                    msg: result
                })
            }
        }
    }
}

//视频上传
exports.postUpload = async (req, res) => {
    let { user_id, title, url, path, isopen, create_time, posting } = req.body
    let arr = [user_id, title, url, path, isopen, create_time, posting]
    db.sqlConnect('insert into post(user_id, title, url, path, isopen, create_time, posting) values(?,?,?,?,?,?,?)', arr, (err, result) => {
        if (err) {
            console.log(err)
            return
        }
        console.log(result)
        if (result?.affectedRows != 0) {
            return res.send({
                code: '200',
                msg: '上传成功'
            })
        }
        return res.send({
            code: '200',
            msg: '上传失败'
        })
    })

}
